<template>
	<view class="chat-container">
		<custom-top></custom-top>
		<!-- 聊天顶部信息 -->
		<view class="therapist-info">
			<view class="flex align-start">
				<image
				src="/src/static/zr/back.png"
				mode=""
				style="width: 60upx; height: 60upx;"
				@click="handelBack"
				/>
				<image :src="therapist?.url" class="avatar" mode="aspectFill" @click="handelSelf"></image>
				<text class="iconfont icon-gengduo2" style="font-size: 50upx;" @click="handelMore"></text>
			</view>
			<view class="info-text padding-top">
				<text class="name">{{ therapist?.name }}</text>
				<text class="status-tag" v-if="therapist?.statusTag">
					<text class="tag-icon" v-if="therapist?.statusTag.icon">:</text>
					{{ therapist?.statusTag.text }}
				</text>
				<text class="bio">{{ therapist?.bio }}</text>
				<!-- 标签区域 -->
				<view class="tag-group">
					<text v-for="(tag, index) in therapist?.tags" :key="index" class="tag-item">
						{{ tag }}
					</text>
				</view>
			</view>
		</view>

		<!-- 聊天消息区域 -->
		<view class="chat-messages" ref="messageContainer">
			<!-- 加载提示 -->
			<view class="loading-tip" v-if="isLoading">加载中...</view>


			<!-- 消息列表 -->
			<view v-for="(msg, index) in messages" :key="msg.timestamp" :class="['message-item', `message-${msg.sender}`]">
				<!-- 对方头像（仅对方消息显示） -->
				<image v-if="msg.sender === 'other'" :src="therapist?.url" class="message-avatar" mode="aspectFill">
				</image>

				<!-- 消息内容 -->
				<view class="">
					<view class="message-content">
						<text>{{ msg.content }}</text>
					</view>
					<text class="message-time margin-right">{{ formatTime(msg.timestamp) }}</text>
				</view>
			</view>
			<!-- AI 思考提示 -->
			<view class="loading-tip" v-if="isAITinking">AI 思考中...</view>

			<!-- 没有消息时的提示 -->
			<view class="empty-tip" v-if="messages.length === 0 && !isLoading">
				开始你的第一次对话吧~
			</view>
		</view>

		<!-- 输入框区域 -->
		<view class="cu-bar foot bg-white flex align-end padding-sm" style="background-color: #fff;">
			<text class="iconfont icon-piaoliuping padding-right-sm margin-bottom-sm" style="font-size: 27px;"></text>
			<!-- <input v-model="message" placeholder="请输入消息..." class="flex-sub" style="height: 35px;align-items: center"/> -->
			<textarea
				  v-model="message"
				  auto-height  
				  class="flex-sub margin-right-sm padding-sm"
				  style="min-height: 27px;max-height: 150px;overflow: auto;line-height: 27px;background-color: #f4f4f4;border-radius: 5px;"
				  placeholder="请输入消息..."
				></textarea>
			<button v-if="message.trim()" @click="handleSend" class="cu-btn bg-blue block" style="margin-bottom: 15upx;">

				发送
			</button>
			<text v-else class="iconfont icon-tianjia_huaban margin-bottom-sm" style="font-size: 27px;"></text>
		</view>
	</view>
</template>

<script setup lang="ts">
import { getChatUser, updateChatList } from '@/api/chat';
import type { chaterType } from '@/model/chat';
import { onLoad } from '@dcloudio/uni-app';
import { ref, onMounted, nextTick, watch} from 'vue'
import type {Ref} from 'vue'
import type { Message } from '@/model/message';
import { getHistoryMessages as apiGetHistory, postsendMessage as apiSendMessage, dbchat } from '@/api/message';
import { useAccount } from '@/store/user';
import { getUserInfo } from '@/api/user';
//对话者id
const { otherid,objectId } = defineProps<{ otherid: string,objectId:string }>();
// 治愈师信息
const therapist:Ref<chaterType|null> = ref(null);
// 消息列表
const messages = ref<Message[]>([]);
// 输入框内容
const message = ref('');
// 加载状态
const isLoading = ref(false);
// 消息容器引用
const messageContainer = ref<HTMLElement | null>(null);
// 是否是当前用户
const isSelf = ref(true);
// 账号信息
const account = useAccount();
// AI 思考状态
const isAITinking = ref(false);
// AI上下文联系
interface ChatMessage { 
  role: string; 
  content: string; 
}
const aiChatList = ref<ChatMessage[]>([]) 


// 修改发送消息逻辑，添加调用大模型接口
const sendMessage = async (content: string, chatId: string) => {
    if (!content.trim() || !chatId) return;

    // 1. 创建临时消息（立即展示提升体验）
    const newMessage: Message = {
        content: content.trim(),
        sender: isSelf.value ? 'self' : 'other',
        timestamp: Date.now(),
        senderId: account.userinfo?.objectId,
        chatId  // 增加chatId关联（根据实际Message类型调整）
    };
    messages.value.push(newMessage);

    try {
        // 2. 调用真实发送API
        const response = await apiSendMessage(newMessage);
        console.log('发送消息', response);
        getLatestMessage(messages.value, objectId);

        // 调用远程大模型接口
        isAITinking.value = true;
        const aiResponse = await dbchat({ 
            message: newMessage.content, 
            history: aiChatList.value
        });
        isAITinking.value = false;
        console.log('AI回复消息', aiResponse);
		// 3. 处理 AI 回复
        if (aiResponse.success) {
            // 创建 AI 回复消息对象
            const aiMessage:Message = {
                content: aiResponse.reply,
                sender: 'other',
                timestamp: Date.now(),
                chatId
            };
            // 将 AI 回复消息存入数据库
            const aiResponseFromApi = await apiSendMessage(aiMessage);
            console.log('发送AI回复消息', aiResponseFromApi);
            
            // 添加到消息列表
            messages.value.push(aiMessage);
			if (aiResponse.newHistory && aiResponse.newHistory.length > 0) {
                aiChatList.value.push(...aiResponse.newHistory);
            }
            // 获取本次对话的最新消息
            getLatestMessage(messages.value, objectId);
        }
        return newMessage;
    } catch (error) {
        console.error('发送消息失败:', error);
        uni.showToast({ 
            title: '发送失败，请重试', 
            icon: 'none', 
        });

        // 移除临时消息
        const tempIndex = messages.value.findIndex(msg => msg.timestamp === newMessage.timestamp);
        if (tempIndex !== -1) {
            messages.value.splice(tempIndex, 1);
        }
        return null;
    } finally {
        isAITinking.value = false;
    }
}
// 切换当前用户
const handelSelf = ()=>{
	isSelf.value = !isSelf.value;
	console.log('切换当前用户',isSelf.value);
	uni.showToast({
		title: '切换当前用户'+isSelf.value,
		icon: 'none',
	})
}
//获取最新消息
const getLatestMessage = async(sortedMessages:Message[], objectId:string)=>{

	  if (sortedMessages.length > 0) {
      const latestMessage = sortedMessages[sortedMessages.length - 1];
      const { content, timestamp } = latestMessage;
      try {
        // 更新 Chats 表数据，假设存在 apiUpdateChats 方法
        await updateChatList(objectId, { lastMessage: content, lastMessageTime: timestamp } as chaterType);
        console.log('Chats 表更新成功');
      } catch (updateError) {
        console.error('Chats 表更新失败:', updateError);
      }
    }
    return sortedMessages;
}
// 历史消息加载（优化用户体验）
const fetchHistoryMessages = async (chatId: string) => {
  if (!chatId) return;
  
  isLoading.value = true;
  try {
    // 调用真实API
    const response = await apiGetHistory(chatId);
    // 确保消息按时间戳正序排列（避免后端返回顺序混乱）
	console.log('获取历史消息',response.data.results);
    const sortedMessages = (response.data.results || []).map((item:any) => item).sort((a: Message, b: Message) => {
      return a.timestamp - b.timestamp;
    });
	// sortedMessages.forEach((item:any) => {
	// 	if(item.senderId == account.userinfo?.objectId){
	// 		item.sender = 'self';
	// 	}else{
	// 		item.sender = 'other';
	// 	}
	// 	return item;
	// })
	sortedMessages.forEach((item:any) => {
      // 修改 sender 判断逻辑
      item.sender = item.senderId === account.userinfo?.objectId ? 'self' : 'other';
      return item;
    })

    messages.value = sortedMessages;
	// 获取最新消息
	getLatestMessage(sortedMessages, objectId);
    return sortedMessages;
  } catch (error) {
    console.error('获取历史消息失败:', error);
    uni.showToast({
      title: '加载历史消息失败',
      icon: 'none',
      duration: 2000
    });
    return [];
  } finally {
    isLoading.value = false;
  }
};

// 格式化时间显示
const formatTime = (timestamp: number): string => {
	const date = new Date(timestamp);
	return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

//发送消息
const handleSend = async () => {
  const chatId = 'chat_' + ( otherid || 'default');
  // 在发送前先清空输入框
  const content = message.value;
  message.value = '';
  let newMessage = await sendMessage(content, chatId);
};

// 返回
const handelBack = () => {
	uni.navigateBack({
		delta: 1
	});
};

// 更多操作
const handelMore = () => {
	uni.showActionSheet({
		itemList: ['分享', '收藏', '报告问题'],
		success: (res) => {
			console.log(res);
		}
	});
};

// 页面加载时获取历史消息
onMounted(async () => {
//   const chatId = 'chat_' + (account.userinfo.objectId);
  const chatId = 'chat_' + (otherid);
  console.log(chatId)
  await fetchHistoryMessages(chatId);
});

onLoad(async(options) => {
	let id = options?.otherid==account.userinfo?.objectId?options?.selfid:options?.otherid;

	let res = await getChatUser(options?.objectId);
	// let res = await getUserInfo(id);

	console.log('获取顶部用户详情',res);
	// 对话者id
	therapist.value = {
		...res.data,
		url:res.data?.avatar||res.data.url
	}
})
</script>

<style lang="scss">
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #ffffff;
	// padding-bottom: 70px;
}

.therapist-info {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #fff;
	border-bottom: 1px solid #eee;

	.flex {
		justify-content: space-between;
		width: 100%;
		padding: 10upx 20upx;
		box-sizing: border-box;
	}

	.avatar {
		width: 60px;
		height: 60px;
		border-radius: 50%;
		border: 2px solid #f0f0f0;
	}

	.info-text {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 0 15px 15px;
		width: 100%;
		box-sizing: border-box;

		.name {
			font-size: 18px;
			font-weight: bold;
			margin-bottom: 4px;
		}

		.status-tag {
			font-size: 14px;
			color: #4CAF50;
			margin-bottom: 4px;
			display: flex;
			align-items: center;
		}

		.tag-icon {
			margin-right: 2px;
		}

		.bio {
			font-size: 14px;
			color: #666;
			margin-bottom: 8px;
			text-align: center;
		}

		// 标签组样式
		.tag-group {
			display: flex;
			flex-wrap: wrap;
			justify-content: center;
			width: 100%;

			.tag-item {
				background-color: #f5f5f5;
				color: #666;
				font-size: 12px;
				padding: 4px 8px;
				border-radius: 4px;
				margin-right: 8px;
				margin-bottom: 8px;
			}
		}
	}
}

.chat-messages {
	flex: 1;
	overflow-y: auto;
	padding: 15px;
	padding-bottom: 65px;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;

	.loading-tip {
		text-align: center;
		padding: 10px;
		color: #999;
		font-size: 14px;
	}

	.empty-tip {
		text-align: center;
		padding: 30px;
		color: #999;
		font-size: 14px;
		margin-top: auto;
		margin-bottom: auto;
	}

	.message-item {
		margin-bottom: 15px;
		display: flex;
		// max-width: 80%;
		animation: fadeIn 0.3s ease;
	}

	// 对方消息样式（左侧）
	.message-other {
		align-self: flex-start;
		margin-right: auto;
	}

	// 自己消息样式（右侧）
	.message-self {
		align-self: flex-end;
		margin-left: auto;
		flex-direction: row-reverse;
	}

	.message-avatar {
		width: 40px !important;
		height: 40px !important;
		border-radius: 50%;
		margin-right: 10px;
		// margin-top: 5px;
	}

	.message-content {
		padding: 10px 15px;
		border-radius: 18px;
		position: relative;
		word-break: break-word;
		line-height: 1.5;
		max-width: 500upx;
	}

	// 对方消息气泡样式
	.message-other .message-content {
		background-color: #ffffff;
		border: 1px solid #eee;
	}

	// 自己消息气泡样式
	.message-self .message-content {
		background-color: #007aff;
		color: white;
	}

	.message-time {
		display: block;
		font-size: 12px;
		margin-top: 5px;
		opacity: 0.7;
		text-align: right;
	}
}
// 消息淡入动画
@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(10px);
	}

	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.input-area {
	display: flex;
	padding: 10px;
	border-top: 1px solid #eee;
}
</style>